package xdu.lz.stage7_jucCollection.lock_free;

import lombok.Data;

/**
 * Created at 2019/10/30 0030 上午 11:58
 * un-thread-safe
 */
public class MyQueue<E> {

    @Data
    private static class Node<E>{
        private E element;
        private Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }

    private Node<E> first,last;
    private int size;

    public int getSize() {
        return size;
    }
    public boolean isEmpty(){
        return size == 0;
    }

    public E peekFirst() {
        return first == null ? null : first.element;
    }

    public E getLast() {
        return last == null? null : last.element;
    }

    public void add(E e){
        Node<E> newNode = new Node<>(e,null);
        if(size == 0){
            first = newNode;
        }else {
            last.next = newNode;
        }
        last = newNode;
        size ++;

    }
    public void addLast(E e){
        add(e);
    }

    public E poll(){
        if(isEmpty()){
            return null;
        }
        E res = first.element;
        //如果空了，要更改last
        if(--size == 0){
            last = null;
        }
        first = first.next;
        return res;
    }
    public E removeFirst(){
        return poll();
    }

    public static void main(String[] args) {
        MyQueue<Integer> queue = new MyQueue<>();
        for (int i = 0; i < 10; i++) {
            queue.add(i);
        }
        while (!queue.isEmpty()){
            System.out.println(queue.poll());
        }
    }
}
